package edu.cs.usask.ca.silver.plugin.rcp.handlers.create;

import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.cs.usask.ca.silver.businesslogic.ids.ModelVersionID;
import edu.cs.usask.ca.silver.plugin.rcp.Activator;
import edu.cs.usask.ca.silver.plugin.rcp.components.SilverNameEnums;
import edu.cs.usask.ca.silver.plugin.rcp.dialogs.create.CreateScenarioCollectionDialog;
import edu.cs.usask.ca.silver.plugin.rcp.handlers.create.helper.CreateDataProcedures;
import edu.cs.usask.ca.silver.plugin.rcp.jobs.LoggerReportScheduler;
import edu.cs.usask.ca.silver.plugin.rcp.views.projectviewer.ProjectViewI;

public class CreateScenarioCollectionHandler extends AbstractHandler {

	private static Logger logger = Logger.getLogger(CreateScenarioCollectionHandler.class);
	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		ProjectViewI view = (ProjectViewI) HandlerUtil
				.getActiveWorkbenchWindow(event).getActivePage()
				.findView(event.getParameter("projectviewid"));

		ModelVersionID selectedParentModelVersionID = (ModelVersionID) view
				.getTreeSelectionAsSilverTreeObject().getSilverObjectId();

		CreateScenarioCollectionDialog dialog = new CreateScenarioCollectionDialog(
				Activator.getDefault().getWorkbench()
						.getActiveWorkbenchWindow().getShell(),
				selectedParentModelVersionID);
		dialog.create();
		try {
			if (view.checkIfSelectedIsOfSpecifiedType(SilverNameEnums.MODELVERSIONID)) {

				if (dialog.open() == Window.OK) {
					CreateDataProcedures
							.createNewScFromCreateScDialogwithAModelVersionIdSelected(
									dialog, view.getAssociatedStorage());
					view.updateTree();
				}
			} else {
				MessageDialog
						.openConfirm(
								dialog.getShell(),
								"Please select a Model Version",
								"Please select a Model Version from project view in order to create a Scenario Collection. You may have selected multiple elements from the tree.");
			}
		} catch (ClassNotFoundException e) {
			LoggerReportScheduler.scheduleErrorLogging(logger,"error while creating scenario collection in rcp command handler", e);
		}
		
		return null;
	}

}
